package com.klangner.math.ast;

/**
 * Each node in expression graph implements this interface
 * To browse node use visitor pattern:
 * http://en.wikipedia.org/wiki/Visitor_pattern
 * 
 * @author Krzysztof Langner
 */
public abstract class Node {

	private String 	text;
	private Node 	firstChild = null;
	private Node 	secondChild = null;

	
	/**
	 * Protected constructor. This class can't be created outside package
	 * @param text
	 */
	protected Node(String text){
		this.text = text;
	}
	
	
	/**
	 * @return node text
	 */
	public String getText(){
		return text;
	}
	
	
	/**
	 * @return first child
	 */
	public Node getFirstChild(){
		return firstChild;
	}
	
	
	/**
	 * @return second child
	 */
	public Node getSecondChild(){
		return secondChild;
	}
	
	
	/**
	 * Compare 2 nodes. Compare expression not objects
	 */
	public boolean isTheSame(Node node){
		return (toString().compareTo(node.toString()) == 0);
	}
	
	
	/**
	 * @return first child
	 */
	public void setFirstChild(Node node){
		this.firstChild = node;
	}
	
	
	/**
	 * @return second child
	 */
	public void setSecondChild(Node node){
		this.secondChild = node;
	}
	
	
	/**
	 * Convert node and its children to string
	 */
	public String toString(){

		String output = "";
		
		if(firstChild != null)
			output +=  firstChild;
		
		output += text;

		if(secondChild != null)
			output +=  secondChild;

		return output;
	}
	
	
	/**
	 * Visitor pattern implementation
	 * @param visitor
	 */
	public abstract Node transform(Transform t);
	
	
	/**
	 * Transform children for given node. Helper function 
	 * @param transform
	 * @param node
	 */
	protected void transformChildren(Transform transform){
	
		if(null != firstChild)
			firstChild = firstChild.transform(transform);
		
		if(null != secondChild)
			secondChild = secondChild.transform(transform);
		
	}
	
}
